const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const mount = require('koa-mount')
const bodyparser = require('koa-bodyparser')  // 不支持form-data 需要借助formidable或 koa-better-body
// koa-compress 启用gzip压缩 数据压缩

// error handler
onerror(app)

// middlewares
// setting up POST to receive data format. POSt请求body数据的解析器
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
// JSON response mimddleware. converts node object streams to binary
app.use(json()) 
// app.use(logger())

// 开放静态资源
const static = require('koa-static')
app.use(mount('/assets', static(__dirname + '/views/assets')))

// 页面模板
const ejs = require('ejs')
app.use(views(__dirname + '/views/pages', {
  extension: 'ejs'
}))



// 页面路由
const pagesRouters = require('./routes/index')
app.use(pagesRouters.backend.routes())

// 特殊处理
app.use(async (ctx, next) => {
    // 404默认跳转
    if(ctx.response.status === 404){
        console.log(ctx.status)
        ctx.redirect('/b/v1/home')
    }
    next()
})

// logge
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()0
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })



// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
